package com.tod.controllers;

import com.tod.message.MessageProcessingHandler;
import com.tod.util.Tools;
import com.tod.util.WeChatUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by tod.tao on 2015/10/16.
 */
@Controller
public class WeChatController {

    @Autowired
    private MessageProcessingHandler messageProcessingHandler;

    private static Logger log = LoggerFactory.getLogger(WeChatController.class);

    @RequestMapping(value = "/wechat",method = RequestMethod.GET)
    @ResponseBody
    public String getMessage(HttpServletRequest request,ModelMap model) {
        String path = request.getServletPath();
        String pathInfo = path.substring(path.lastIndexOf("/"));
        String _token;
        String outPut = "error";
        if (pathInfo != null) {
            _token = pathInfo.substring(1);
            String signature = request.getParameter("signature");// 微信加密签名
            String timestamp = request.getParameter("timestamp");// 时间戳
            String nonce = request.getParameter("nonce");// 随机数
            String echostr = request.getParameter("echostr");//
            // 验证
            if (WeChatUtil.checkSignature(_token, signature, timestamp, nonce)) {
                outPut = echostr;
            }
        }
        return outPut;
    }

    @RequestMapping(value = "/wechat",method = RequestMethod.POST)
    @ResponseBody
    public String postMessage(HttpServletRequest request,HttpServletResponse response,ModelMap model)throws IOException {
        ServletInputStream in = request.getInputStream();
        String xmlMsg = Tools.inputStream2String(in);
        log.info("输入消息:[" + xmlMsg + "]");
        String xml = WeChatUtil.processing(messageProcessingHandler,xmlMsg);
        log.info("输出消息:[" + xml + "]");
        return xml;
    }
}
